﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ColdSun.Services;
using ColdSun.Commons.Entities;
using ColdSun.Commons.Configs;
using ColdSun.Commons;
using System.IO;

namespace ColdSun.BankManagements
{
    public partial class FrmExport : Form
    {
        private FrmProgressBar frmProgressBar = new FrmProgressBar(); 
        public FrmExport()
        {
            InitializeComponent();
        }

        private void Export_Load(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(Utilities.GetFullFileName(CommonConfigs.DefaultOriginalFile)))
            {
                txtOriginalExportFile.Text = Utilities.GetFullFileName(CommonConfigs.DefaultOriginalFile);
            }
            if (System.IO.File.Exists(Utilities.GetFullFileName(CommonConfigs.DefaultFollowingFile)))
            {
                txtFollowingFile.Text = Utilities.GetFullFileName(CommonConfigs.DefaultFollowingFile);
            }
            if (System.IO.Directory.Exists(Utilities.GetFullFileName(CommonConfigs.DefaultExportFolder)))
            {
                txtExportFolder.Text = Utilities.GetFullFileName(CommonConfigs.DefaultExportFolder);
            }
            dtpReportDate.Format = DateTimePickerFormat.Custom;
            dtpReportDate.CustomFormat = "dd/MM/yyyy";
            txtReportDepartments.Text = CommonConfigs.DefaultExportDepartments;

            //Replacement
            txtReplaceOriginalExcelFile.Text = Utilities.GetFullFileName(CommonConfigs.ServiceDeskUserOPOriginalExcelFile);
            txtReplaceReplaceInfoFile.Text = Utilities.GetFullFileName(CommonConfigs.ServiceDeskUserOPInfoFile);
            txtReplaceWordTemplateFile.Text = Utilities.GetFullFileName(CommonConfigs.ServiceDeskUserOPWordTemplateFile);
            txtReplaceExportWordFile.Text = CommonConfigs.ServiceDeskUserOPExportFile;
            txtReplaceExportFolder.Text = Utilities.GetFullFileName(CommonConfigs.ServiceDeskUserExportFolder);
            dtpReplaceDate.Format = DateTimePickerFormat.Custom;
            dtpReplaceDate.CustomFormat = "dd/MM/yyyy";
        }

        #region Export
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportToDoc();
        }

        private void ExportToDoc()
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundExportWorker_DoWork);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundExportWorker_RunWorkerCompleted);

            // Kick off the Async thread
            backgroundWorker.RunWorkerAsync();

            // Lock up the UI with this modal progress form.
            frmProgressBar.ShowDialog();
        }

        private void BackgroundExportWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            ExportAccountService excelService = new ExportAccountService();
            string reportDays = txtReportDays.Text;
            if (cbUsingReportDate.Checked)
            {
                reportDays = dtpReportDate.Value.ToString("dd");
            }
            string[] reportDeparments = null;
            if (!cbReportAllDepartments.Checked)
            {
                reportDeparments = txtReportDepartments.Text.Trim().Split(',');
            }

            string result = excelService.GenerateExport(
                txtOriginalExportFile.Text,
                txtFollowingFile.Text,
                dtpReportDate.Value,
                reportDays,
                reportDeparments,
                txtExportFolder.Text);
            //frmProgressBar.Close();
        }

        private void BackgroundExportWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (frmProgressBar != null)
            {
                frmProgressBar.Close();
            }
        }

        private void cbUsingReportDate_CheckedChanged(object sender, EventArgs e)
        {
            if (cbUsingReportDate.Checked)
            {
                txtReportDays.Visible = false;
            }
            else
            {
                txtReportDays.Visible = true;
            }
        }

        private void btnOriginalExportFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter = "Excel Files (.xlsx)|*.xlsx|Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;

            if(openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtOriginalExportFile.Text = openFileDialog.FileName;
            }
        }

        private void btnFollowingFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter = "Excel Files (.xlsx)|*.xlsx|Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtFollowingFile.Text = openFileDialog.FileName;
            }
        }

        private void btnExportFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtExportFolder.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void cbReportAllDepartments_CheckedChanged(object sender, EventArgs e)
        {
            if (cbReportAllDepartments.Checked)
            {
                txtReportDepartments.Visible = false;
            }
            else
            {
                txtReportDepartments.Visible = true;
            }
        }
        #endregion

        #region Replace Params
        private void ReplaceParamsInDoc()
        {
            Replacement replace = new Replacement();
            replace.SheetName = "Sheet1";
            replace.Details = new List<ReplacementDetail>();
            replace.Details.Add(new ReplacementDetail());
            replace.Details[0].ColumnName = "ColumnName";
            replace.Details[0].RowIndex = 1;
            replace.Details[0].ReplaceParam = "param";

            string result = XmlUtility.SerializeObject<Replacement>(replace);
            MessageBox.Show(result);
        }

        private void btnReplaceOriginalExcelFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter = "Excel Files (.xlsx)|*.xlsx|Excel Files (.xls)|*.xls|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtReplaceOriginalExcelFile.Text = openFileDialog.FileName;
            }
        }

        private void btnReplaceWordTemplateFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter = "Excel Files (.docx)|*.docx|Excel Files (.doc)|*.doc|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 2;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtReplaceWordTemplateFile.Text = openFileDialog.FileName;
            }
        }

        private void btnReplaceReplaceInfoFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            // Set filter options and filter index.
            openFileDialog.Filter = "Xml Files (.xml)|*.xml|All Files (*.*)|*.*";
            openFileDialog.FilterIndex = 1;

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                txtReplaceReplaceInfoFile.Text = openFileDialog.FileName;
            }
        }

        private void btnReplaceExportFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                txtReplaceExportFolder.Text = folderBrowserDialog.SelectedPath;
            }
        }

        private void btnReplaceExport_Click(object sender, EventArgs e)
        {
            BackgroundWorker backgroundWorker = new BackgroundWorker();
            backgroundWorker.DoWork += new DoWorkEventHandler(BackgroundReplaceWorker_DoWork);
            backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(BackgroundReplaceWorker_RunWorkerCompleted);

            // Kick off the Async thread
            backgroundWorker.RunWorkerAsync();

            // Lock up the UI with this modal progress form.
            frmProgressBar.ShowDialog();
        }

        private void BackgroundReplaceWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            List<Replacement> replacementInfos = GetReplacementInfo(txtReplaceReplaceInfoFile.Text);
            //List<Replacement> list = new List<Replacement>();
            //list.Add(replacementInfo);
            //string s = XmlUtility.SerializeObject<List<Replacement>>(list);
            //MessageBox.Show(s);
            try
            {
                ReplacementService service = new ReplacementService();
                string result = service.ReplaceTextsInWordFile(
                    txtReplaceOriginalExcelFile.Text, txtReplaceWordTemplateFile.Text, replacementInfos,
                    dtpReplaceDate.Value, txtReplaceExportWordFile.Text, txtReplaceExportFolder.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }

        private void BackgroundReplaceWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (frmProgressBar != null)
            {
                frmProgressBar.Close();
            }
        }

        private List<Replacement> GetReplacementInfo(string file)
        {
            try
            {
                TextReader tr = new StreamReader(file);
                string xmlString = tr.ReadToEnd();
                return XmlUtility.DeserializeObject<List<Replacement>>(xmlString);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error");
            }
            return null;
        }
        #endregion

        private void mnuAbout_Click(object sender, EventArgs e)
        {
            FrmAbout frmAbout = new FrmAbout();
            frmAbout.ShowDialog();
        }
    }
}
